﻿using System;
using System.Text.RegularExpressions;

namespace XSerialization.Generator
{
    public static class ConvertUtilities
    {
        /// <summary>
        /// Convert XSD Names to C# Names
        /// </summary>
        /// <param name="name">XSD Name</param>
        /// <returns>C# Name</returns>
        public static string ConvertXsdName(string name)
        {
            if (string.IsNullOrEmpty(name)) return name;

            //remove pre strings like T_xyz
            int charIndex = name.IndexOf("_");
            if (charIndex > 0 && charIndex < name.Length) name = name.Substring(charIndex + 1);

            //remove forbidden chars
            name = Regex.Replace(name, " *[\\~#%&*{}/:<>?|\"-]+ *", "");
            //first char to upper
            name = Char.ToUpperInvariant(name[0]) + name.Substring(1);
            return name;
        }

        /// <summary>
        /// Convert XSD simple Types to C# Types
        /// </summary>
        /// <param name="typeName">XSD Type Name</param>
        /// <param name="isRequired">Null allowed</param>
        /// <returns>C# Type Name</returns>
        public static string ConvertSimpleTypes(string typeName, bool isRequired)
        {
            string newName = typeName.Replace("xs:", "");

            switch (newName.ToLower())
            {
                case "integer":
                    {
                        newName = "int";
                        break;
                    }
                case "nonnegativeinteger":
                    {
                        newName = "uint";
                        break;
                    }
                case "positiveinteger":
                    {
                        newName = "uint";
                        break;
                    }
                case "boolean":
                    {
                        newName = "bool";
                        break;
                    }
                case "decimal":
                    {
                        newName = "double";
                        break;
                    }
                case "unsignedshort":
                    {
                        newName = "ushort";
                        break;
                    }
                case "datetime":
                    {
                        newName = "DateTime";
                        break;
                    }
            }

            if (!isRequired && newName != "string")
            {
                newName = newName + "?";
            }

            return newName;
        }
    }
}
